//
//  CycleTool+Convert.m
//  CDSBZX
//
//  Created by dihuijun on 17/3/2.
//  Copyright © 2017年 Cycle. All rights reserved.
//

#import "CycleTool+Convert.h"

@implementation CycleTool (Convert)
/**
 *  1. 字典转Json字符串
 *  @param infoDict id类型
 */
+ (NSString *)Cycle_ConvertToJSONData:(id)infoDict{
    //1.1 定义错误
    NSError *error;
    //1.2 将字典转化成 NSData类型
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:infoDict options:NSJSONWritingPrettyPrinted error:&error];
    //1.3 定义一个空的要接收的字符串
    NSString *jsonString = @"";
    //1.4 判断jsonData是否为空
    if (!jsonData) {
        NSLog(@"Got an error:%@",error);
    }else{
        //如果有值，将NSData转化成 NSString
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    //1.5 去掉换行和空格
    jsonString = [jsonString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    //去掉 "\n" 这种换行
    [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    
    return jsonString;
}

/**
 *  2. JSON字符串转化为字典
 *  @param jsonString NSString类型
 */
+ (NSDictionary *)Cycle_Convert_DictionaryWithJsonString:(NSString *)jsonString;{
    if (kisNilString(jsonString)) {
        NSLog(@"jsonString 为空");
        return nil;
    }
    //将字符串转化为NSData
    NSData *jsonData  = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error;
    //将NSData转化为NSDictionary
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
    
    if (error) {
        NSLog(@"json解析失败：%@",error);
        return nil;
    }
    
    
    return dict;
    
    
    
    
}

@end
